﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.Net.Mail;
using InstrumentCheck.Module;
using InstrumentCheck.BLL;
using InstrumentCheck.ILocalService;
using System.Workflow.Activities;
using System.Workflow.Runtime;
using System.Workflow.Runtime.Hosting;

namespace InstrumentCheck.WebAppUI
{
    public partial class CorrectItem : BasePage
    {
        User UserInfo = null; 
        protected void Page_Load(object sender, EventArgs e)
        {
            Session["AttachList"] = null;
            UserInfo = Session["UserInfo"] as User;
            if (!Page.IsPostBack)
            {
                ViewState["ID"] = Request["ID"];               

                if (Session["Routing"] != null)
                    Session.Remove("Routing");

                if (Session["Form"] != null)
                    Session.Remove("Form");

                if (ViewState["ID"] == null)
                    ShowPageValue();
                else
                    ShowPageValueWithID(int.Parse(ViewState["ID"].ToString()));
            }
        }       

        private void ShowPageValue()
        {
            ApplyForm form = new ApplyForm();
            Item item = new Item();
            item.ItemAttachment = new List<Attach>();
            form.Item = item;
            Session["Form"] = form;

            divFlowDesc.Style.Add("display", "none");
            FormRouting routing = GenerateRouting();
            Session["Routing"] = routing;
            lblFormNO.Text = "Auto Number";
            lblCreaterInfo.Text = UserInfo.EmpChineseName + " - " + UserInfo.DeptNO + " - " + UserInfo.ExtNO;
            lblApplicant.Text = UserInfo.EmpChineseName + " - " + UserInfo.ExtNO;
            txtApplicantNO.Text = UserInfo.EmpNO;
            lblApplyDept.Text = UserInfo.DeptNO;
            lblApplyDate.Text = DateTime.Today.ToString("yyyy/MM/dd");
            imgSend.Visible = true;
            imgSave.Visible = true;
            pnlHistory.Visible = false;
            pnlRemark.Visible = false;
            ViewState["AttachURL"] = "uploadAttach.aspx";
            ViewState["ImageURL"] = "uploadImage.aspx";
        }

        private void ShowPageValueWithID(int ID)
        {
            ApplyForm form = Form_bll.GetFormDetailByID(ID);
            Session["Form"] = form;
            if (form.FormNO > 0)
                lblFormNO.Text = form.FormNO.ToString("0000000000");
            else
                lblFormNO.Text = "Auto Number";
            User creater = form.Creater;
            User applicant = form.Applicant;

            lblCreaterInfo.Text = creater.EmpChineseName + " - " + creater.DeptNO + " - " + creater.ExtNO;

            lblApplicant.Text = applicant.EmpChineseName + " - " + applicant.ExtNO;
            lblApplyDept.Text = applicant.DeptNO;
            lblApplyDate.Text = form.ApplyDate.ToString("yyyy/MM/dd");
            if (form.FormType == FormType.New)
                chkNew.Checked = true;
            else if (form.FormType == FormType.Change)
                chkModify.Checked = true;
            txtApplyReason.Text = form.ApplyReason;
            txtApplicantNO.Text = applicant.EmpNO;

            Item item = form.Item;
            User keeper = item.Keeper;
            ddlAssetType.SelectedValue = Convert.ToString((int)item.AssetType);
            txtAssetNO.Text = item.AssetNO;
            if (keeper != null)
            {
                lblKeepDept.Text = keeper.DeptNO;
                lblKeeper.Text = keeper.EmpChineseName;
            }
            lblChiName.Text = item.ChiName;
            lblBrand.Text = item.Brand;
            lblSpec.Text = item.Spec;
            lblModuleNO.Text = item.ModelNO;
            txtPRNO.Text = item.PRNO;
            if(item.BuyDate.HasValue)
            txtBuyDate.Text = item.BuyDate.Value.ToString("yyyy/MM/dd");
            if (item.CurrencyType.HasValue)
                ddlBuyCurrency.SelectedValue = item.CurrencyType.ToString();
            if (item.BuyAmount.HasValue)
                txtBuyAmount.Text = item.BuyAmount.ToString();

            if(item.FirstCorrectTime.HasValue)
            txtFirstCorrectDate.Text = item.FirstCorrectTime.Value.ToString("yyyy/MM/dd");
            if (item.CorrectCurrencyType.HasValue)
                ddlCorrectCurrency.SelectedValue = item.CorrectCurrencyType.ToString();
            txtCorrectAmount.Text = item.CorrectAmount.ToString();
            if(item.NeedCorrectDate.HasValue)
            txtNeedCorrectDate.Text = item.NeedCorrectDate.Value.ToString("yyyy/MM/dd");
            if(item.CorrectCycle.HasValue)
                ddlCorrectCycle.SelectedValue = Convert.ToString((int)item.CorrectCycle);
            if(item.CurrentStatus.HasValue)
                ddlCurrentStatus.Value = Convert.ToString((int)item.CurrentStatus);
            if(item.CorrectType.HasValue)
                ddlCorrectType.SelectedValue = Convert.ToString((int)item.CorrectType);

            if (item.CorrectResult.HasValue)
                ddlCorrectStatus.SelectedValue = Convert.ToString((int)item.CorrectResult);
            txtStandard.Text = item.Standard;
            txtRemark.Text = item.Remark;

            ShowAttach(item.ItemAttachment);
            if (IsInApprovingRouting(form.FormRoutingHistory))
            {
                imgAgree.Visible = true;
                imgDisagree.Visible = true;
                pnlRemark.Visible = true;
            }
            else
            {
                divFlowDesc.Style.Add("display", "none");
                pnlRemark.Visible = false;
            }

            if (UserInfo.EmpNO == creater.EmpNO && form.FormStatus == FormStatus.Processing)
                imgWithDraw.Visible = true;
            if (form.FormNO == 0)
                imgSave.Visible = true;
            else
            {
                lblHistory.Text = Form_bll.GenerateFormHistory(form);
                pnlHistory.Visible = true;
            }

            FormRouting routing = Session["Routing"] as FormRouting;
            if (routing == null)
                routing = new FormRouting {FlowNO=-1 };
            switch (routing.FlowNO)
            {
                case 10:
                    InitialControlState(true);
                    break;
                case 20:
                    InitialControlState(true);
                    ddlCorrectStatus.Enabled = true;
                    break;
                case 30:
                    InitialControlState(false);
                    break;
                default :
                    InitialControlState(true);
                    break;
            }
            if (form.FormStatus == FormStatus.Draft)
            {
                InitialControlState(false);
                imgSend.Visible = true;
                chkNew.Enabled = true;
                chkModify.Enabled = true;
                imgApplicant.Disabled = false;
                ddlAssetType.Enabled = true;
                routing = new FormRouting { FlowNO =0 };
                txtApplyReason.ReadOnly = false;
                imgAssetNO.Disabled = false;
            }

            string strAttach = "", strImage = "";
            if (item.ItemAttachment.Count > 0)
            {
                List<Attach> list = item.ItemAttachment;
                for (int i = 0; i < list.Count; i++)
                {
                    if (list[i].Type == AttachmentType.Attachment)
                        strAttach += list[i].SystemName + "~" + list[i].ClientName + ";";
                    else if (list[i].Type == AttachmentType.Picture)
                        strImage += list[i].SystemName + "~" + list[i].ClientName + ";";
                }
                txtAttachInfo.Text = strAttach;
                txtImageInfo.Text = strImage;
            }

            ViewState["AttachURL"] = "uploadAttach.aspx?NO=" + ViewState["ID"].ToString();
            ViewState["ImageURL"] = "uploadImage.aspx?NO=" + ViewState["ID"].ToString();
            Session["Routing"] = routing;
        }

        protected void imgSend_Click(object sender, ImageClickEventArgs e)
        {
            //产生form的资料并保存到DB
            try
            {
                CheckBeforeSend(txtAssetNO.Text,chkModify.Checked);                
            }
            catch(Exception ex)
            {
                AlertMessage(ex.Message);                
                return;
            }


            try
            {                
                ApplyForm form = GenerateForm();
                FormRouting routing = GenerateRouting();
                Form_bll.Send(form, routing, this.PageURL(), UserInfo.Email);
            }
            catch
            {
                throw;
            }

            this.AlertMessage("表單已傳送！","default.aspx");
        }

        public void CheckBeforeSend(string assetNO,bool IsChange)
        {
            if(lblCorrectAttach.Text == "" && txtAttachInfo.Text.Length > 0)
                ShowAttachmentWithText(txtAttachInfo.Text.Split(';'), lblCorrectAttach);
            if(lblCorrectPictures.Text == "" && txtImageInfo.Text.Length > 0)
                ShowAttachmentWithText(txtImageInfo.Text.Split(';'), lblCorrectPictures);
            if (!IsChange)
            {
                bool flag = Asset_bll.IsInProcessing(assetNO);
                if (flag)
                    throw new Exception("對不起，該資產編號已經在簽核中了，不能重複申請！");
            }

            bool ExistFlag = Asset_bll.ExistInItem(assetNO);
            if (IsChange && !ExistFlag)
                throw new Exception("對不起，資產編號不存在資料基本檔中，不可以申請change！");

            if (!IsChange && ExistFlag)
                throw new Exception("對不起，資料已經存在資料基本檔中，不可以重複申請！");
        }

        #region 送出表單之前產生表單的相信信息
        private ApplyForm GenerateForm()
        {
            FormRouting routing = Session["Routing"] as FormRouting;
            ApplyForm form = Session["Form"] as ApplyForm;
            if (form == null)
                form = new ApplyForm();
            Item item = new Item();
            item.AssetNO = txtAssetNO.Text.Trim();
            item.ChiName = lblChiName.Text;
            item.ModelNO = lblModuleNO.Text;
            item.Spec = lblSpec.Text;
            if(ddlAssetType.SelectedItem.Value.ToString() != "")
                item.AssetType = (AssetType)int.Parse(ddlAssetType.SelectedItem.Value);
            item.PRNO = txtPRNO.Text.Trim();
            if(txtBuyDate.Text.Trim().Length > 0)
                item.BuyDate = Convert.ToDateTime(txtBuyDate.Text.Trim());

            if (ddlBuyCurrency.SelectedIndex != 0)  //购买币别
                item.CurrencyType = (CurrencyType)Enum.Parse(typeof(CurrencyType), ddlBuyCurrency.SelectedItem.Value);

            if (txtBuyAmount.Text.Trim() != "")   //购买金额
                item.BuyAmount = Convert.ToDouble(txtBuyAmount.Text.Trim());

            if(txtFirstCorrectDate.Text.Trim().Length > 0)
                item.FirstCorrectTime = Convert.ToDateTime(txtFirstCorrectDate.Text.Trim());

            if (ddlCorrectCurrency.SelectedIndex != 0) //校验币别
                item.CorrectCurrencyType = (CurrencyType)Enum.Parse(typeof(CurrencyType), ddlCorrectCurrency.SelectedItem.Value);

            if(txtCorrectAmount.Text.Trim().Length > 0)
                item.CorrectAmount = double.Parse(txtCorrectAmount.Text.Trim());  //校验费用

            if(txtNeedCorrectDate.Text.Trim().Length > 0)
                item.NeedCorrectDate = Convert.ToDateTime(txtNeedCorrectDate.Text.Trim());
            if(ddlCorrectCycle.SelectedItem.Value.ToString() != "")
                item.CorrectCycle = (CorrectCycle)int.Parse(ddlCorrectCycle.SelectedItem.Value);
            if(ddlCurrentStatus.Value.ToString() != "")
                item.CurrentStatus = (AssetStatus)int.Parse(ddlCurrentStatus.Value);
            if(ddlCorrectType.SelectedItem.Value.ToString() != "")
            item.CorrectType = (CorrectType)int.Parse(ddlCorrectType.SelectedItem.Value);
            if(ddlCorrectStatus.SelectedItem.Value.ToString() != "")
                item.CorrectResult = (CorrectResult)int.Parse(ddlCorrectStatus.SelectedItem.Value);
            item.Standard = txtStandard.Text.Trim();
            item.Remark = txtRemark.Text.Trim();

            item.ItemAttachment = new List<Attach>();
            AddAttachment(item, txtAttachInfo.Text.Trim().Split(';'), AttachmentType.Attachment);
            AddAttachment(item, txtImageInfo.Text.Trim().Split(';'), AttachmentType.Picture);

            //ApplyForm form = new ApplyForm();
            if (routing.FlowNO == 0)
            {
                User applicant = new User();
                applicant.EmpNO = txtApplicantNO.Text;
                form.Applicant = applicant;
                form.ApplyDate = DateTime.Now;
                form.ApplyReason = txtApplyReason.Text.Trim();
                form.Creater = UserInfo;

                form.FormNO = 0;
                if (chkNew.Checked)
                    form.FormType = FormType.New;
                else if (chkModify.Checked)
                    form.FormType = FormType.Change;
            }
            form.Item = item;
                        
            form.FormStatus = FormStatus.Processing;
            if (ViewState["ID"] != null)
                form.FormID = int.Parse(ViewState["ID"].ToString());
            Session["Form"] = form;
            return form;
        }
        private void AddAttachment(Item item, string[] aryAttach, AttachmentType type)
        {
            foreach (string str in aryAttach)
            {
                string[] strAttach = str.Split('~');
                if (strAttach[0] == "")
                    break;
                Attach attach = new Attach();
                int intFormNO;
                int.TryParse(lblFormNO.Text.Trim(), out intFormNO);
                attach.FormNO = intFormNO;
                attach.SystemName = strAttach[0];
                attach.ClientName = strAttach[1];
                attach.Type = type;
                item.ItemAttachment.Add(attach);
            }
        }
        private FormRouting GenerateRouting()
        {
            FormRouting routing = new FormRouting();
            routing.FlowNO = 0;
            return routing;
        }
        #endregion

        #region 進入表單的頁面show出表單的具體信息
        private void ShowAttach(List<Attach> list)
        {
            string strAttach = "", strImage = "";
            string strURL = this.PageURL();
            for (int i = 0; i < list.Count; i++)
            {
                Attach attach = list[i];
                if (attach.Type == AttachmentType.Attachment)
                    strAttach += "<a target='_blank' href='" + strURL + "/Attachment/" + attach.SystemName + "'>" + attach.ClientName + "</a>;";
                else if (attach.Type == AttachmentType.Picture)
                    strImage += "<a target='_blank' href='" + strURL + "/Attachment/" + attach.SystemName + "'>" + attach.ClientName + "</a>;";
            }
            lblCorrectAttach.Text = strAttach;
            lblCorrectPictures.Text = strImage;
        }
        public bool IsInApprovingRouting(List<FormRouting> list)
        {
            //if (list == null)
            //    return false;
            for (int i = 0; i < list.Count;i++ )
            {
                FormRouting routing = list[i];                
                if (!routing.ApproveResult.HasValue)
                    continue;
                if (routing.ApproveResult.Value != ApproveResult.Approving)
                    continue;
                User receiver = routing.Receiver;
                lblFlowDesc.Text = routing.FlowName;
                
                if (receiver.EmpNO == UserInfo.EmpNO || routing.AgentNO == UserInfo.EmpNO)
                {
                    Session["Routing"] = routing;
                    return true;
                }
            }
            return false;
        }
        #endregion

        public void InitialControlState(bool NeedDisable)
        {
            //除了申請之外，其餘都不可以修改的部份
            chkModify.Enabled = false;
            chkNew.Enabled = false;
            txtApplyReason.ReadOnly = true;
            ddlAssetType.Enabled = false;
            imgApplicant.Disabled = true;
            imgAssetNO.Disabled = true;

            //根據條件可以修改的部份
            imgFindPR.Disabled = NeedDisable;
            txtBuyDate.Enabled = !NeedDisable;
            txtFirstCorrectDate.Enabled = !NeedDisable;
            txtNeedCorrectDate.Enabled = !NeedDisable;
            ddlBuyCurrency.Enabled = !NeedDisable;
            ddlCorrectCurrency.Enabled = !NeedDisable;
            txtBuyAmount.ReadOnly = NeedDisable;
            txtCorrectAmount.ReadOnly = NeedDisable;
            ddlCorrectCycle.Enabled = !NeedDisable;
            ddlCurrentStatus.Disabled = NeedDisable;
            ddlCorrectType.Enabled = !NeedDisable;
            ddlCorrectStatus.Enabled = !NeedDisable;
            txtStandard.ReadOnly = NeedDisable;
            txtRemark.ReadOnly = NeedDisable;            
        }

        protected void imgAgree_Click(object sender, ImageClickEventArgs e)
        {
            FormRouting routing = Session["Routing"] as FormRouting;
            try
            {
                ApplyForm form = Session["Form"] as ApplyForm;
              
                routing.Approver = UserInfo;
                routing.ApproverDate = DateTime.Now;
                routing.ApproveResult = ApproveResult.Agree;
                routing.ApproveStatus = ApproveStatus.Approved;
                routing.Remark = txtRoutingRemark.Text;

                int flowNO = routing.FlowNO;
                Item item = form.Item;
               
                if(flowNO == 20 && ddlCorrectStatus.SelectedItem.Value.ToString() != "")
                    item.CorrectResult = (CorrectResult)Enum.Parse(typeof(CorrectResult), ddlCorrectStatus.SelectedItem.Value);

                if (flowNO == 30)
                    form = GenerateForm();

                Form_bll.Approve(form, routing, this.PageURL(), UserInfo.Email);                         
            }
            catch
            {
                throw;
            }
            this.AlertMessage("表單已傳送！"," default.aspx");
        }

        protected void imgWithDraw_Click(object sender, ImageClickEventArgs e)
        {
            FormRouting routing = Session["Routing"] as FormRouting;
            ApplyForm form = Session["Form"] as ApplyForm;

            routing.FormNO = int.Parse(lblFormNO.Text);
            routing.ApproveResult = ApproveResult.WithDraw;

            try
            {
                Form_bll.CancelForm(form,this.PageURL(),UserInfo.Email);
            }
            catch(Exception ex)
            {
                AlertMessage("撤銷中發生錯誤。錯誤信息：" + ex.Message.ToString());
                throw;
            }
            this.AlertMessage("成功撤銷該表單！","default.aspx");        
        }

        protected void imgSave_Click(object sender, ImageClickEventArgs e)
        {
            try
            {                
                ApplyForm form = GenerateForm();
                FormRouting routing = GenerateRouting();
                Form_bll.Save(form);
            }
            catch
            {
                throw;
            }
            this.AlertMessage("表單已保存！","default.aspx");
        }

        protected void btnChange_Click(object sender, EventArgs e)
        {
            string strAssetNO = txtAssetNO.Text.Trim();
            bool flag = Asset_bll.IsInProcessing(strAssetNO);
            if (flag)
            {
                AlertMessage("該資產編號已經在簽核中了！");
                txtAssetNO.Text = "";
                return;
            }

            Item item = Asset_bll.GetItemInfoByAssetNO(strAssetNO);
            if(item != null)
                ShowItemInfo(item);
            ShowAttachmentWithText(txtAttachInfo.Text.Split(';'), lblCorrectAttach);
            ShowAttachmentWithText(txtImageInfo.Text.Split(';'), lblCorrectPictures);
        }
        private void ShowItemInfo(Item item)
        {
            lblKeepDept.Text = item.Keeper.DeptNO;
            lblKeeper.Text = item.Keeper.EmpChineseName;
            lblChiName.Text = item.ChiName;
            lblBrand.Text = item.Brand;
            lblSpec.Text = item.Spec;
            lblModuleNO.Text = item.ModelNO;
            txtPRNO.Text = item.PRNO;
            txtBuyDate.Text = item.BuyDate.Value.ToString("yyyy/MM/dd");
            txtFirstCorrectDate.Text = item.FirstCorrectTime.Value.ToString("yyyy/MM/dd");
            txtNeedCorrectDate.Text = item.NeedCorrectDate.Value.ToString("yyyy/MM/dd");
            ddlAssetType.SelectedValue = Convert.ToString((int)item.AssetType);
            if (item.CorrectCurrencyType.HasValue)
                ddlCorrectCurrency.SelectedValue = item.CorrectCurrencyType.Value.ToString();
            if (item.CurrencyType.HasValue)
                ddlBuyCurrency.SelectedValue = item.CurrencyType.Value.ToString();
            if (item.BuyAmount.HasValue)
                txtBuyAmount.Text = item.BuyAmount.Value.ToString();
            if (item.CorrectAmount.HasValue)
                txtCorrectAmount.Text = item.CorrectAmount.Value.ToString();
            if (item.CorrectCycle.HasValue)
                ddlCorrectCycle.SelectedValue = Convert.ToString((int)item.CorrectCycle.Value);
            if (item.CurrentStatus.HasValue)
            {
                ddlCurrentStatus.Value = Convert.ToString((int)item.CurrentStatus.Value);
                txtCurrentStatus.Text = Convert.ToString((int)item.CurrentStatus.Value);
            }
            if (item.CorrectType.HasValue)
                ddlCorrectType.SelectedValue = Convert.ToString((int)item.CorrectType.Value);
            if (item.CorrectResult.HasValue)
                ddlCorrectStatus.SelectedValue = Convert.ToString((int)item.CorrectResult.Value);
            txtStandard.Text = item.Standard;
            txtRemark.Text = item.Remark;
        }

        private void ShowAttachmentWithText(string[] aryAttach,Label lbl)
        {
            //根据Textbox中的信息显示附近的链接
            string strURL = "";
            foreach (string str in aryAttach)
            {
                string[] strAttach = str.Split('~');
                if (strAttach[0] == "")
                    break;
                strURL += "<a target='_blank' href='" + this.PageURL() + "/" + System.Configuration.ConfigurationManager.AppSettings["AttachPath"].ToString() + "/" + strAttach[0] + "'>" + strAttach[1] + "</a>;";
            }
            lbl.Text = strURL;
        }

    }
}
